# -*- coding:utf-8 -*-
import json
import sys
import string
import random
import hashlib
import time
import MySQLdb
from com.zzh.utils.dbUtils import MysqlUtils
class authTokenOperation(object):
    def __init__(self):  # 类初始化。
         self.conn = MysqlUtils.get_mysql_connections_v2()  #

    def generateToken(self, loginPhone, password):
        curGenerateToken = self.conn.cursor()
        sql = "select user_password from zzh_user where user_phone=%s"

        result = curGenerateToken.execute(sql, [loginPhone])
        if not result:
            return 0, None  # 0-用户不存在
        else:
            login_reult = curGenerateToken.fetchone()
            pwd = login_reult[0]
            radonNumber = random.randint(1, 1000)
            if (pwd == password):
                hs= loginPhone + " " + pwd + str(radonNumber)
                token = str(hashlib.sha1(hs).hexdigest()) # 直接用用户手机号加密码加一个随机字母生成token，
                startTime = time.time()
                sql2 = "UPDATE zzh_user SET token=%s ,startTime=%s WHERE user_phone=%s"
                rs = curGenerateToken.execute(sql2, [token, startTime, loginPhone])
                self.conn.commit()



            else:


                return -1, None
        curGenerateToken.close()
        self.conn.close()
        return rs, token


    def veryfyToken(self, token):
        tokenA = token
        currentTimeYM = time.time()

        curToken = self.conn.cursor()
        sqlA = "SELECT token,duration,startTime FROM zzh_user WHERE token = %s"

        result = curToken.execute(sqlA,[tokenA])
        if result:
            data = curToken.fetchone()
            tokenB = data[0]
            duration = data[1]
            startTime = data[2]
            curToken.close()
            self.conn.close()
        else:
            verifyResult = 0
            curToken.close()
            self.conn.close()
            return verifyResult


        if ((tokenA == tokenB ) and (int(currentTimeYM - startTime) < int(duration))):#判定合法性，
            verifyResult = 1#只有token相等且生存时间内，则返回1，
            return verifyResult
        else:#其他情况验证失败
            verifyResult = 0
            return verifyResult
